package com.pmlt.controller;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.lang.Assert;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.pmlt.common.lang.Result;
import com.pmlt.entity.User;
import com.pmlt.service.UserService;
import org.apache.shiro.authz.annotation.RequiresAuthentication;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import java.time.LocalDateTime;

/**
 * <p>
 *  前端控制器
 * </p>
 *
 * @author tlp
 * @since 2021-12-22
 */
@RestController
@RequestMapping("/user")
public class UserController {

    @Autowired
    UserService userService;

    @GetMapping("/users")
    public Result list(@RequestParam(defaultValue = "1") Integer currentPage) {
        Page page = new Page(currentPage, 5);
        IPage pageData = userService.page(page, new QueryWrapper<User>().orderByDesc("created"));
        return Result.succ(pageData);
    }

    @GetMapping("/{id}")
    public Result detail(@PathVariable(name = "id") Long id) {
        User user = userService.getById(id);
        Assert.notNull(user, "无用户");
        return Result.succ(user);
    }

    @RequiresAuthentication
    @PostMapping("/edit")
    public Result edit(@Validated @RequestBody User user) {
        User temp = null;
        if (user.getId() != null) { // 编辑用户
            temp = userService.getById(user.getId());
        }else { // 新建用户
            temp = new User();
            temp.setCreated(LocalDateTime.now());
        }
        // temp.setLastLogin(LocalDateTime.now());
        BeanUtil.copyProperties(user, temp, "id", "created");
        userService.saveOrUpdate(temp);
        return Result.succ(user);
    }

    // 需要认证后才能进行删除
    @RequiresAuthentication
    @GetMapping("/del/{id}")
    public Result del(@PathVariable Long id) {
        boolean b = userService.removeById(id);
        if (b == true) {
            return Result.succ("删除成功！");
        }
        return Result.fail("该id不存在，请核对后进行编辑！");
    }

}
